<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\logic;

use app\common\model\OtcCancelLog;
use app\common\model\OtcOrder;
use app\common\model\OtcShop;
use app\common\model\OtcTrading;
use app\common\model\SbNotice;
use app\common\model\Transfer;
use app\common\model\UserAccountLog;
use app\common\model\UserPayType;
use app\common\model\UserSms;
use app\common\model\UserRankingData;
use app\common\model\WithdrawalPayinfo;
use think\Db;

/**
 * Recharge逻辑
 */
class Appstore extends LogicBase
{
    

    
    /**
     * 获取游戏币总转换列表
     */
    public function game_coin_list($data = [], $field = 'a.*,c.username ', $order = '', $paginate = DB_LIST_ROWS)
    {
        


        $where = $where1 = [];
        if (!empty($data['date1']) && !empty($data['date2'])) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if (!empty($data['search_data'])) {
            $where1['a.user_id'] = $data['search_data'];
            $where1['c.username'] =['like','%'.$data['search_data'].'%'] ;
        }
        if (!empty($data['form_wallet_id'])) {
            $where['a.form_wallet_id'] = $data['form_wallet_id'];
        }

        $where['a.status'] =1;
        $where['a.type'] =8;
//        if (!empty($data['game_id'])) {
//            $where['a.game_id'] = $data['game_id'];
//        }

        if (!empty($where1)) {

            $list =  $this->modelTransfer->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->where(function ($q)use($where1){
                $q->whereOr($where1);
            })->order($order)->paginate($paginate, false, ['query' => $data]);
            $count =  $this->modelTransfer->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->where(function ($q)use($where1){
                $q->whereOr($where1);
            })->count();

        } else {

            $list =  $this->modelTransfer->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);
            $count =  $this->modelTransfer->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->count();
        }

        $ke=$this->modelTransfer->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->sum('number');

        $ke=$ke?$ke:0;

        return ['count'=>$count,'list'=>$list,'ke'=>$ke];



    }



    /**


    /**
     * 兑换游戏币审核
     */
    public function setStatus($data=[])
    {

        $info = $this->modelTransfer->getInfo(['id' => $data['id']]);
        Db::startTrans();
        try {


            if ($data['state'] == 1) {
                //审核通过
                    return [RESULT_ERROR, '暂未开放该功能'];



            }else{
                //账户变动
                $useracount = $this->modelUserAccount->where(['wallet_id' => $info['form_wallet_id'], 'user_id' => $info['user_id']])->lock(true)->find();
                $useracount->balance += $info['number'];
                $useracount->save();
                if($info['type']==5){
                    $data['before_available_balance'] = $useracount->balance - $info['number'];
                    $data['after_available_balance'] = $useracount->balance;
                }

                if($info['type']==6){
                    $data['before_against_balance'] = $useracount->balance - $info['number'];
                    $data['after_against_balance'] = $useracount->balance;
                }


                //写入流水
                UserAccountLog::create([
                    'user_id' => $info['user_id'],
                    'number' => $info['number'],
                    'wallet_id' =>  $info['form_wallet_id'],
                    'before_blance' => $useracount->balance - $info['number'],
                    'after_blance' => $useracount->balance,
                    'is_add' => 1,
                    'type' => 2
                ]);
            }

            $result = $this->modelTransfer->setInfo($data);
            $msg = $data['state'] == 1 ? '审核成功' : '拒绝审核';
            $result && action_log('兑换游戏币审核审核', $msg);
            Db::commit();
            return $result ? [RESULT_SUCCESS, '审核成功'] : [RESULT_ERROR, '审核失败'];

        } catch (\Exception $e) {
            Db::rollback();
            return [RESULT_ERROR, $e->getMessage()];
        }
    }


    /**
     * 获取总包提现区块链列表
     */
    public function wallet_withdrawal_list($data = [], $field = 'a.*,c.username ', $order = '', $paginate = DB_LIST_ROWS)
    {



        $where = $where1 = [];
        if (!empty($data['date1']) && !empty($data['date2'])) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if (!empty($data['search_data'])) {
            $where1['a.user_id'] = $data['search_data'];
            $where1['c.username'] =['like','%'.$data['search_data'].'%'] ;
        }
        if (!empty($data['form_wallet_id'])) {
            $where['a.form_wallet_id'] = $data['form_wallet_id'];
        }
        if (isset($data['state'])) {
            if(!empty($data['state']) || $data['state']=='0'){
                $where['a.state'] = $data['state'];
            }
        }
        $where['a.status'] =1;
        $where['a.type'] =3;

        if (!empty($where1)) {

            $list =  $this->modelTransfer->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->where(function ($q)use($where1){
                $q->whereOr($where1);
            })->order($order)->paginate($paginate, false, ['query' => $data]);
            $count =  $this->modelTransfer->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->where(function ($q)use($where1){
                $q->whereOr($where1);
            })->count();

        } else {

            $list =  $this->modelTransfer->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);

            $count =  $this->modelTransfer->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->count();
        }
        $where2=['state'=>1,'type'=>3];

        if (!empty($data['date_type'])){
            switch ($data['date_type']){
                case  1:
                    //今日
                    $where2['create_time']=['between',[getTodayStart(),getTodayEnd()]];


                    break;
                case  2:
                    //昨日
                    $where2['create_time']=['between',[getTodayStart()-86400,getTodayEnd()-86400]];

                    break;
                case  3:
                    //近七天
                    $where2['create_time']=['between',[getTodayStart()-86400*7,getTodayEnd()]];

                    break;
                case  4:
                    //近30天
                    $where2['create_time']=['between',[getTodayStart()-86400*30,getTodayEnd()]];

                    break;

            }
        }
        //提现次数
        $arr['account1']=$this->modelTransfer->where($where2)->count();
        //提现总金额
        $arr['account2']=$this->modelTransfer->where($where2)->sum('number')+0;
        //商家代发金额
        $where2['is_otc']=1;
        $arr['account3']=$this->modelTransfer->where($where2)->sum('number')+0;
        //系统提现金额
        $where2['is_otc']=0;
        $arr['account4']=$this->modelTransfer->where($where2)->sum('number')+0;



        return ['count'=>$count,'list'=>$list,'arr'=>$arr];



    }


    /**
     * 导出总包提现到钱包记录
     */
    public function exportWalletWithdrawalList($data, $field = 'a.*,c.username', $order = 'create_time desc, id desc')
    {
        $where = $where1 = [];
        if (!empty($data['date1']) && !empty($data['date2'])) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if (!empty($data['search_data'])) {
            $where1['a.user_id'] = $data['search_data'];
            $where1['c.username'] =['like','%'.$data['search_data'].'%'] ;
        }
        if (!empty($data['form_wallet_id'])) {
            $where['a.form_wallet_id'] = $data['form_wallet_id'];
        }
        if (isset($data['state'])) {
            if(!empty($data['state']) || $data['state']=='0'){
                $where['a.state'] = $data['state'];
            }
        }
        if (!empty($data['paytype'])) {
            $where['b.type'] = $data['paytype'];
        }else{
            $where['b.type'] = ['lt',4];
        }
        $where['a.status'] =1;
        $where['a.type'] =3;
//        if (!empty($data['game_id'])) {
//            $where['a.game_id'] = $data['game_id'];
//        }

        if (!empty($where1)) {

            $list =  $this->modelTransfer->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__WITHDRAWAL_PAYINFO__ b' ,'a.id = b.withdrawal_id')->field($field)->where($where)->where(function ($q)use($where1){
                $q->whereOr($where1);
            })->order($order)->select();


        } else {

            $list =  $this->modelTransfer->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__WITHDRAWAL_PAYINFO__ b' ,'a.id = b.withdrawal_id')->field($field)->where($where)->order($order)->select();

        }
        if (!empty($data['paytype']) && $data['paytype']==4) {
            foreach ($list as $k => $v) {
                $list[$k]['k'] = $k+1;
                $list[$k]['wallet_name'] = $v->withpay->data['name'];
                $list[$k]['state_text'] = $v->state_text;
                if($v['update_time']){
                    $v['up_time']=date('Y-m-d H:i:s',$v['update_time']);
                }else{
                    $v['up_time']='';
                }
            }

            $titles = "序号,ID,用户账号,用户ID,钱包类型,提现金额,提现地址,交易哈希,到账币种数额,提现时间,状态,审核时间,审核人";
            $keys = "k,id,username,user_id,wallet_name,money,to,hash,number,create_time,state_text,up_time,admin_name";
            action_log('导出', '导出总包提现到线下钱包记录');
            export_excel($titles, $keys, $list, '总包提现到线下钱包记录');
        }else{
            foreach ($list as $k => $v) {
                $list[$k]['k'] = $k+1;
                $list[$k]['type_name'] = $v->withpay->type_text;
                $list[$k]['bank_card'] = $v->withpay->bank_card;
                $list[$k]['state_text'] = $v->state_text;
                if($v['update_time']){
                    $v['up_time']=date('Y-m-d H:i:s',$v['update_time']);
                }else{
                    $v['up_time']='';
                }
            }

            $titles = "序号,ID,用户账号,用户ID,支付类型,账号/卡号,提现金额,提现时间,状态,审核时间,审核人";
            $keys = "k,id,username,user_id,type_name,bank_card,money,create_time,state_text,up_time,admin_name";
            action_log('导出', '导出总包提现到法币记录');
            export_excel($titles, $keys, $list, '总包提现到法币记录');
        }




    }

    public function  pay_list($data){
        $info= $this->modelTransfer->getInfo(['id' => $data['id']]);
        $paylist=json_decode($info['pay_json'],true);
        foreach ($paylist as $k =>$v){
            if($v['type']==$data['type']){
                switch ($v['type']){
                    case 1:
                        $paylist[$k]['pay_text'] = '支付宝';
                        $paylist[$k]['pay_name'] = '支付宝';
                        break;
                    case 2:
                        $paylist[$k]['pay_text'] = '微信';
                        $paylist[$k]['pay_name'] = '微信';
                        break;
                    case 3:
                        $paylist[$k]['pay_text'] = '银行卡';
                        $paylist[$k]['pay_name'] = '银行卡';
                        break;

                }
            }else{
                unset( $paylist[$k]);
            }

        }

        return $paylist;
    }


    /**
     * 交易审核
     */
    public function trade_check($data=[])
    {





        $info = $this->modelTransfer->getInfo(['id' => $data['id']]);

        Db::startTrans();
        try {
            $eth_account= $this->modelUserAccount->where(['user_id'=>$info['user_id'],'wallet_id'=>1])->lock(true)->find();


            if ($data['state'] == 4) {
                //审核通过
                $money_price=getPrice();
                if(!in_array($info['money'],$money_price)){
                    return  [RESULT_ERROR, '当前提现金额不能通过审核'];
                }
                $data['is_otc']=1;

            }elseif($data['state']==2){
                //拒绝审核
                $eth_account->balance+=$info['money'];
                $eth_account->save();

                //写入流水
                UserAccountLog::create([
                    'user_id' => $info['user_id'],
                    'number' => $info['number'],
                    'wallet_id' => $eth_account['wallet_id'],
                    'before_blance' =>   $eth_account->balance -$info['number'],
                    'after_blance' =>   $eth_account->balance,
                    'is_add' => 1,
                    'remark' => '提现失败退回',
                    'type' => 5
                ]);

            }elseif ($data['state']==6){
                //商家打款

                if(empty($data['cover_id'])){
                    return  [RESULT_ERROR, '请上传打款截图'];
                }

                $arr['pay_time']=TIME_NOW;
                $arr['state']=3;
                $arr['cover_id']=$data['cover_id'];
                $arr['receive_expire_time']=time()+getConfig('otc_order_recieve_time')*60;
                SbNotice::create([
                    'type'=>3,
                    'expire_time'=>$arr['receive_expire_time'],
                    'order_id'=>$info->otco_rder['id'],
                    'wallet_id'=>$info->otco_rder['wallet_id'],
                    'user_id'=>$info->otco_rder['uid'],

                ]);
                Db::name('otc_order')->where(['id'=>$info->otco_rder['id']])->update($arr);


            }
            $data['admin_name']=  session('member_info.username');
            $result = $this->modelTransfer->setInfo($data);
            switch ($data['state']){
                case 1:
                    $msg ='提现成功';
                    break;
                case 2:
                    $msg ='提现失败';
                    break;
                case 4:
                    $msg ='审核通过';
                    break;
                case 6:
                    $msg ='商家打款';
                    break;
            }
            $result && action_log('提现操作', $msg);
            Db::commit();
            return $result ? [RESULT_SUCCESS, '操作成功'] : [RESULT_ERROR, '操作失败'];

        } catch (\Exception $e) {
            Db::rollback();
            return [RESULT_ERROR, $e->getMessage()];
        }
    }


    /***
     * 匹配订单
     */

    public  function  match_order($data){
        $info = $this->modelTransfer->getInfo(['id' => $data['id']]);
        Db::startTrans();
        try {
            //生成订单
            //写入订单记录
            $uid=$info['user_id'];
            $money=$info['number'];
            $member = $this->modelMember->getInfo($uid);

            // $where=['c.is_black'=>0,'a.type'=>1];
            // $where['s.is_match']=1;
            // $where['s.shop_switch']=1;
            // $where['a.surplus_total']=$money;
            // $where['a.state']=0;
            // $where['s.id']=$data['shop_id'];
            // $where['a.user_id']=['neq',$uid];
            // $order=OtcTrading::alias('a')->field("a.*,surplus_total AS new_price,a.surplus_number , a.price as all_price")->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->where($where)->order("feed_count desc ,match_count asc ,price asc ,id asc")->find();
            // if(!$order){
            //     unset( $where['a.user_id']);
            //     $where['c.is_company']=1;
            //     $order=OtcTrading::alias('a')->field("a.*,surplus_total AS new_price,a.surplus_number , a.price as all_price")->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->where($where)->order("feed_count desc ,match_count asc ,price asc ,id asc")->find();

            // }
            // if(!$order){
            //     Db::rollback();
            //     return   [RESULT_ERROR, '暂无订单适合匹配'];
            // }

            // $time=time()+getConfig('otc_last_time')*60;


            // //买单总价等于提现金额
            // $number= $order->surplus_number;
            // //写入订单表
            // $arr=[
            //     'price'=>$order['price'],
            //     'wallet_id'=>$order['wallet_id'],
            //     'pay_expire_time'=>$time,
            //     'otc_type'=>$order['type'],
            //     'shop_id'=>$order['shop_id'],
            //     'otc_id'=>$order['id'],
            //     'user_id'=>$order['user_id'],
            //     'pay_json'=>$info['pay_json'],
            //     'uid'=>$uid,
            //     'total'=>$order['new_price'],
            //     'number'=>$number,
            //     'withdrwal_id'=>$info->id,
            //     'channel'=>'CCIE',

            // ];
            $shop = Db::name("otc_shop")->where(["id"=>$data["shop_id"]])->find();
            $price = Db::name("wallet")->where(["id"=>$shop["wallet_id"]])->find()['parities'];
            $number = $money/$price;
            $time=time()+getConfig('otc_last_time')*60;
                //写入订单表
            
            $arr=[
                'price'=>$price,
                'wallet_id'=>$shop['wallet_id'],
                'pay_expire_time'=>$time,
                'otc_type'=>1,
                'shop_id'=>$data['shop_id'],
                // 'otc_id'=>$order['id'],
                'user_id'=>$shop['user_id'],
                'pay_json'=>$info['pay_json'],
                'uid'=>$uid,
                'total'=>$money,
                'number'=>$number,
                'withdrwal_id'=>$info->id,
                'channel'=>'CCIE',

            ];




            $poundage=getConfig('otc_receive_poundage')/100;
            $arr['poundage_number']=$arr['number']*$poundage;
            $or=OtcOrder::create($arr);
            SbNotice::create([
                'type'=>7,
                'shop_name'=>$shop['shop_name'],
                'number'=>$number,
                'order_id'=>$or->id,
                'user_id'=>$shop['user_id'],
                'expire_time'=>$time,
                'wallet_id'=>$shop['wallet_id']

            ]);
            $info->money=0;
            $info->state=5;
            $info->save();
            Db::name("otc_shop")->where(["id"=>$data["shop_id"]])->setInc("total_count");
            // $order->match_count+=1;
            // $order->surplus_number=0;
            // $order->surplus_total=0;
            // $order->state=1;
            // $order->save();
           
            // $order->shop->total_count+=1;
            // $order->shop->save();
            
            //给商家发送短信
            
            $shop_member = Db::name("member")->where(["id"=>$shop['user_id']])->find();
            $lang = in_array($shop_member['area'], ['86', '852', '853', '886']) ? 'zh-hk' : 'en-us';
            $content=getConfig("otc_shop_match_zh-hk");
            
            $data = [
                'mobile' => $shop_member['mobile'],
                'content' => $content,
                'create_time' => TIME_NOW,
                'sms_type' => 2,
                'type' => 0,
                'area' => $shop_member['area']
            ];
            $sms = UserSms::create($data);

            if (getConfig('sms_is_test') != 1) {
                $state = send_sms($shop_member['mobile'], $content, config('settings'), $shop_member['area']);
                if ($state) {
                    UserSms::where(['id' => $sms->id])->update(['state' => 2]);
                }  
                
            }

            Db::commit();
            return [RESULT_SUCCESS, '匹配成功'];
//
        } catch (\Exception $e) {
            Db::rollback();
            return [RESULT_ERROR, $e->getMessage()];
        }
    }


    /***
     * 提现订单生成
     */
    public  function  otc_order_edit($data){

        $user_name_list = explode("\r\n",$data['username']);
        $money_list = explode("\r\n",  $data['money']);
//        $pay_list = explode("\r\n",  $data['pay_method']);
        $channel=explode(',',$data['channel']);
        if (empty($user_name_list)) {
            return  [RESULT_ERROR, '会员账号不能为空，请重新输入'];

        }
        if (empty($money_list)) {
            return  [RESULT_ERROR, '金额不能为空，请重新输入'];
        }
        if (count($user_name_list) != count($money_list) ) {
            return  [RESULT_ERROR, '会员账号和金额数量行数不相等'];
        }

        $otc_price=getPrice();
        Db::startTrans();
        foreach ($user_name_list as $k=>$v) {
            $member = $this->modelMember->getInfo(['username|mobile' => $v]);
            if (!$member) {
                Db::rollback();
                return [RESULT_ERROR, $v.' 会员账号不存在，请重新输入'];
            }
            if ($member['is_company'] != 1) {
                Db::rollback();
                return [RESULT_ERROR, $v . ' 不是公司账号'];
            }
            if( !in_array($money_list[$k],$otc_price )){
                Db::rollback();
                return [RESULT_ERROR, $money_list[$k].'金额不符合'];
            }
//            $pay_list = $this->modelUserPayType->where(['user_id' => $member['id'],'type'=>$pay_list[$k], 'status' => 1])->select();
//            if (empty($pay_list)) {
//                Db::rollback();
//                return [RESULT_ERROR,$v.' 用户收款方式不存在'];
//            }


            try {
                //生成订单
                //写入订单记录
                $money=$money_list[$k];
                $uid=$member['id'];
                $where=['c.is_black'=>0,'a.type'=>1];
                $ids1=Member::where(['path'=>['like','%,'.$uid.',%']])->column('id');
                $ids2=explode(',',rtrim($member['path'], ","));
                $ids=array_merge($ids1,$ids2);
                $where['a.user_id']=['not in',$ids];
                $where['s.is_match']=1;
                $where['a.surplus_total']=$money;
                $where['a.state']=0;
                $where['s.shop_switch']=1;
                $where['c.start_time_int']=['neq',0];
                $where['c.start_time_int']=['lt',TIME_NOW];
                $where['c.end_time_int']=['neq',0];
                $where['c.end_time_int']=['gt',TIME_NOW];
                $order=OtcTrading::alias('a')->field("a.*,surplus_total AS new_price,a.surplus_number , a.price as all_price")->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->where($where)->order("feed_count desc ,match_count asc ,price asc ,id asc")->find();

                if(!$order){
                    unset( $where['a.user_id']);
                    $where['c.is_company']=1;
                    $where['a.user_id']=['neq',$uid];

                    $order=OtcTrading::alias('a')->field("a.*,surplus_total AS new_price,a.surplus_number , a.price as all_price")->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->where($where)->order("feed_count desc ,match_count asc ,price asc ,id asc")->find();

                }
                if(!$order){
                    Db::rollback();
                    return   [RESULT_ERROR, $v.'暂无订单适合匹配'];
                }


                $time=time()+getConfig('otc_last_time')*60;
                $pays=$payids=[];
                $ali_pay=UserPayType::where(['user_id'=>$order->member['id'],'type'=>1,'status'=>1,'is_use'=>1])->order('use_count asc, id asc')->select();
                $count=0;
                if($ali_pay){
                    if(count($ali_pay)>1){
                        foreach ($ali_pay as $ke=>$va){
                            $money=OtcOrder::where(['uid'=>$order->member['id'],'state'=>['not in',[4,5,13]],'pay_ids'=>['like','%,'.$va['id'].',%']])->sum('total')+0;
                            if($money>$va['max_money']){
                                continue;
                            }else{
                                $payids[]=$va['id'];
                                $pays[]=$va;
                                $count++;
                                break;

                            }
                        }
                    }else{
                        $money=OtcOrder::where(['uid'=>$order->member['id'],'state'=>['not in',[4,5,13]],'pay_ids'=>['like','%,'.$ali_pay[0]['id'].',%']])->sum('total')+0;
                        if($money<$ali_pay[0]['max_money']){

                            $payids[]=$ali_pay[0]['id'];
                            $pays[]=$ali_pay[0];
                            $count++;
                        }

                    }



                }
                $wechat_pay=UserPayType::where(['user_id'=>$order->member['id'],'type'=>2,'status'=>1,'is_use'=>1])->order('use_count asc, id asc')->select();
                if($wechat_pay){
                    if(count($wechat_pay)>1){
                        foreach ($wechat_pay as $ke=>$va){
                            $money=OtcOrder::where(['uid'=>$order->member['id'],'state'=>['not in',[4,5,13]],'pay_ids'=>['like','%,'.$va['id'].',%']])->sum('total')+0;
                            if($money>$v['max_money']){
                                continue;
                            }else{
                                $payids[]=$va['id'];
                                $pays[]=$va;
                                $count++;
                                break;

                            }
                        }
                    }else{
                        $money=OtcOrder::where(['uid'=>$order->member['id'],'state'=>['not in',[4,5,13]],'pay_ids'=>['like','%,'.$wechat_pay[0]['id'].',%']])->sum('total')+0;
                        if($money<$wechat_pay[0]['max_money']){

                            $payids[]=$wechat_pay[0]['id'];
                            $wechat_pay[0]['image']=$wechat_pay[0]->image;
                            $pays[]=$wechat_pay[0];
                            $count++;
                        }

                    }

                }

                $bank_pay=UserPayType::where(['user_id'=>$order->member['id'],'type'=>3,'status'=>1,'is_use'=>1])->order('use_count asc, id asc')->select();
                if($bank_pay){

                    if(count($bank_pay)>1){
                        foreach ($bank_pay as $ke=>$va){
                            $money=OtcOrder::where(['uid'=>$order->member['id'],'state'=>['not in',[4,5,13]],'pay_ids'=>['like','%,'.$va['id'].',%']])->sum('total')+0;
                            if($money>$va['max_money']){
                                continue;
                            }else{
                                $payids[]=$va['id'];
                                $pays[]=$va;
                                $count++;
                                break;

                            }
                        }
                    }else{
                        $money=OtcOrder::where(['uid'=>$order->member['id'],'state'=>['not in',[4,5,13]],'pay_ids'=>['like','%,'.$bank_pay[0]['id'].',%']])->sum('total')+0;
                        if($money<$wechat_pay[0]['max_money']){

                            $payids[]=$bank_pay[0]['id'];
                            $pays[]=$bank_pay[0];
                            $count++;
                        }

                    }
                }

                if($payids){
                    UserPayType::where(['id'=>['in',$payids]])->setInc('use_count',1);
                }
                if($count==0){
                    //禁止匹配
                    $shop=OtcShop::get(['id'=>$order['shop_id']]);
                    if($shop['no_match_time']>time()){
                        $shop['no_match_time']+=86400;
                    }else{
                        $shop['no_match_time']=86400;
                    }
                    $shop->is_match=0;
                    $shop->save();
                    OtcCancelLog::create([
                        'username'=>$order->member['username'],
                        'mobile'=>$order->member['mobile'],
                        'area'=>$order->member['area'],
                        'number'=>1,
                        'type'=>3,
                        'shop_id'=>$shop['id'],
                        'remark'=>'OTC限制店铺匹配(收款金额超过每日限制)',
                        'user_id'=>$order->member['id'],
                        'pay_json'=>json_encode($pays),
                    ]);
                   Db::commit();
                    return   [RESULT_ERROR, '出售订单超过每日收款限额,请重新匹配'];
                }


                $arr=[
                    'number'=>$money,
                    'money'=>0,
                    'type'=>3,
                    'remark'=>'后台生成',
                    'user_id'=>$uid,
                    'form_wallet_id'=>1,
                    'poundage_number'=>0,
                    'state'=>4,
                    'is_otc'=>1
                ];

                $arr['pay_json']=json_encode($pays);

                $result=Transfer::create($arr);
                $withdrwal_order=Transfer::get([$result->id]);


                //买单总价等于提现金额
                $number= $order->surplus_number;
                //写入订单表
                $rndKey = array_rand($channel);
                $arr=[
                    'price'=>$order['price'],
                    'wallet_id'=>$order['wallet_id'],
                    'pay_expire_time'=>$time,
                    'otc_type'=>$order['type'],
                    'shop_id'=>$order['shop_id'],
                    'otc_id'=>$order['id'],
                    'user_id'=>$order['user_id'],
                    'uid'=>$uid,
                    'total'=>$order['new_price'],
                    'number'=>$number,
                    'withdrwal_id'=>$result->id,
                    'pay_json'=>json_encode($pays),
                    'channel'=>$channel[$rndKey]

                ];
                $withdrwal_order->money=0;
                $withdrwal_order->state=5;
                $withdrwal_order->save();
                $or=OtcOrder::create($arr);
                $order->match_count+=1;
                $order->surplus_number=0;
                $order->surplus_total=0;
                $order->state=1;
                $order->save();
                $order->shop->total_count+=1;
                $order->shop->save();


                SbNotice::create([
                    'type'=>7,
                    'shop_name'=>$order->shop->shop_name,
                    'number'=>$number,
                    'order_id'=>$or->id,
                    'user_id'=>$order['user_id'],
                    'expire_time'=>$time,
                    'wallet_id'=>$order['wallet_id']

                ]);

            } catch (\Exception $e) {
                Db::rollback();
                return [RESULT_ERROR, $e->getMessage()];
            }

        }

        $url = url('cash_withdrawal_list');
        Db::commit();
        return [RESULT_SUCCESS, '生成成功', $url];

    }







}
